package com.dc;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MultiRouteDataSource extends AbstractRoutingDataSource {

    private Map<Object, Object> dynamicTargetDataSources = new HashMap<>();

    public static List<String> dataSourceIds = new ArrayList<>();

    @Override
    protected Object determineCurrentLookupKey() {
        // 通过绑定线程的数据源上下文实现多数据源的动态切换
        return DataSourceContext.getDataSource();
    }


    /**
     * 判断指定DataSrouce当前是否存在
     */
    public static boolean containsDataSource(String dataSourceId) {
        return dataSourceIds.contains(dataSourceId);
    }

    @Override
    public void setTargetDataSources(Map<Object, Object> targetDataSources) {
        super.setTargetDataSources(targetDataSources);
        this.dynamicTargetDataSources = targetDataSources;
        super.afterPropertiesSet();
    }


    /**
     * 新增数据源
     *
     * @param defauleDataSourceProperties 数据源
     */
    public void addTargetDataSources(String key, Map defauleDataSourceProperties) {
        DataSourceComponent dataSourceComponent = new DataSourceComponent();
        Class<? extends DataSource> clazz = dataSourceComponent.getDataSourceType("com.alibaba.druid.pool.DruidDataSource");
        DataSource dataSource = dataSourceComponent.bind(clazz, defauleDataSourceProperties);
        dynamicTargetDataSources.put(key, dataSource);
        dataSourceIds.add(key);
        super.setTargetDataSources(dynamicTargetDataSources);
        super.afterPropertiesSet();
    }

}

